package com.jiyinit.web.core.mobile.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.OrgPageRequest;
import com.jiyinit.web.core.business.dto.OrgRequest;
import com.jiyinit.web.core.business.dto.UserRequest;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.CurrentUserVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.*;

/**
 * 部门管理
 *
 * @author zhaolaiwei
 * @version 1.0
 * @date 2017/4/18 9:37
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/morg")
public class MorgController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MorgController.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgService;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    /**
     * 跳转到部门树
     *
     * @param request
     * @return
     */
    @RequestMapping("/toOrgTree")
    public String toFindUserList(HttpServletRequest request) {
        return "/org/orgTree";
    }

    @ResponseBody
    @RequestMapping("/mgetOrgTree")
    public ResponseEntity<ResponseDto> getOrgTree(HttpServletRequest request) {
    	
    	OrgRequest orgRequest = this.getJsonToTaskRequest(request);
    	Integer parentId = orgRequest.getParentId();
        LogUtil.info(LOGGER, "parentId：{}", parentId);
        if (Check.isNullObj(parentId)) {
            parentId = 0;
        }
        List items = this.fillTree(parentId);
        if(items.size()>0){
        	return new ResponseEntity<>(ResponseDto.responseOK(items), HttpStatus.OK);
        }
        return  new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
        
    }

    private List fillTree(Integer parentId) {
        List<TabCoreOrgEntity> orgList = orgService.selectByParentId(parentId);
        List items = new ArrayList<>();
        for (TabCoreOrgEntity tabCoreOrg : orgList) {
            Map map = new HashMap();
            map.put("id", tabCoreOrg.getOrgId());
            map.put("pId", tabCoreOrg.getParentId());
            map.put("name", tabCoreOrg.getOrgName());
            map.put("level", tabCoreOrg.getOrgLevel());
            //map.put("isParent", true);

            List<TabCoreOrgEntity> tempOrgList = orgService.selectByParentId(tabCoreOrg.getOrgId());
            if (!Check.isNullCollection(tempOrgList)) {
                map.put("isParent", true);
            } else {
                map.put("isParent", false);
            }
            items.add(map);
        }
        return items;
    }

    @ResponseBody
    @RequestMapping("/mgetOrgAndPeople")
    public ResponseEntity<ResponseDto> OrgAndPeople(HttpServletRequest request) {
    	
    	OrgRequest orgRequest = this.getJsonToTaskRequest(request);
    	Integer parentId = orgRequest.getParentId();
        LogUtil.info(LOGGER, "parentId：{}", parentId);
        if (Check.isNullObj(parentId)) {
            parentId = 0;
        }
        List items = this.fillTreeAndPeople(parentId);
        if(items.size()>0){
        	return new ResponseEntity<>(ResponseDto.responseOK(items), HttpStatus.OK);
        }
        return  new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
        
    }
    @ResponseBody
    @RequestMapping("/findOrgByLayer")
    public ResponseEntity<ResponseDto> findOrgByLayer(HttpServletRequest request) {
        OrgRequest orgRequest = this.getJsonToTaskRequest(request);
        List<TabCoreOrgEntity> orgList = orgService.selectByParentId(orgRequest.getOrgId());
        List<TabCoreUserEntity> userList = userService.findUserByOrgId(orgRequest.getOrgId());
        HashMap<String,Object> result = new HashMap<>();
        result.put("orgList",orgList);
        result.put("userList",userList);
        return  new ResponseEntity<>(ResponseDto.responseOK(result), HttpStatus.OK);
    }
    
    private List fillTreeAndPeople(Integer parentId) {
        List<TabCoreOrgEntity> orgList = orgService.selectOrgAndPeoByPId(parentId);
        List items = new ArrayList<>();
        for (TabCoreOrgEntity tabCoreOrg : orgList) {
            Map map = new HashMap();
            map.put("id", tabCoreOrg.getOrgId());
            map.put("pId", tabCoreOrg.getParentId());
            map.put("name", tabCoreOrg.getOrgName());
            map.put("clas", tabCoreOrg.getClas());
            map.put("level", tabCoreOrg.getOrgLevel());
            //map.put("isParent", true);
            
            if(tabCoreOrg.getClas()==0){
	            List<TabCoreOrgEntity> tempOrgList = orgService.selectOrgAndPeoByPId(tabCoreOrg.getOrgId());
	            if (!Check.isNullCollection(tempOrgList)) {
	                map.put("isParent", true);
	            } else {
	                map.put("isParent", false);
	            }
            }else{
            	map.put("isParent", false);
            }
            items.add(map);
        }
        return items;
    }
    
    /**
     * 跳转部门管理首页
     *
     * @param request
     * @return
     */
    @RequestMapping("/toOrgMenu")
    public String toOrgMenu(HttpServletRequest request) {
        return "/org/orgMenu";
    }

    /**
     * 通过部门parentId分页查询部门信息
     *
     * @param orgPageRequest
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/getOrgTreeForPage")
    @ResponseBody
    public PagingResult getTreeByParentForPage(OrgPageRequest orgPageRequest) {
        PagingResult<TabCoreOrgEntity> pagingResult = orgService.selectPageByParentId(orgPageRequest);
        return pagingResult;
    }

    /**
     * 跳转添加部门页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/toOrgAdd")
    public String toOrgAdd(HttpServletRequest request, Integer parentId) {
        //根节点
        String parentName = "";
        if (Check.isNullObj(parentId)) {
            parentId = 0;
        }
        if (new Integer(0).equals(parentId)) {
            parentName = "根节点";
        } else {
            TabCoreOrgEntity parentOrg = orgService.selectById(parentId);
            parentName = parentOrg.getOrgName();
        }
        request.setAttribute("parentId", parentId);
        request.setAttribute("parentName", parentName);
        return "/org/orgAdd";
    }

    /**
     * 新增部门
     *
     * @param orgRequest
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/orgAdd")
    @ResponseBody
    public ResponseEntity<ResponseDto> treeAdd(OrgRequest orgRequest) {
        // 校验参数
        ValidateResult<OrgRequest> validateResult = paramCheckLogic.checkParamValidate(orgRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabCoreOrgEntity coreOrg = new TabCoreOrgEntity();
        BeanUtils.copyProperties(orgRequest, coreOrg);

        //判断是否为根节点
        if(!new Integer(0).equals(coreOrg.getParentId())){
            TabCoreOrgEntity parentOrg = orgService.selectById(coreOrg.getParentId());
            coreOrg.setOrgLevel(parentOrg.getOrgLevel() + 1);
        } else {
            coreOrg.setOrgLevel(new Integer(0));
        }

        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        Integer userId = currentUser.getUserId();
        coreOrg.setOrgStatus(new Integer(1));
        coreOrg.setIsDelete(new Integer(0));
        coreOrg.setCreateId(userId);
        coreOrg.setCreateTime(new Date());
        coreOrg.setLastModifyId(userId);
        coreOrg.setLastModifyTime(new Date());
        int num = orgService.save(coreOrg,coreOrg.getParentId());
        if (num == 1) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("系统错误"), HttpStatus.OK);
    }


    /**
     * 跳转修改部门页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/toOrgUpdate")
    public String toOrgUpdate(HttpServletRequest request, Integer orgId) {
        TabCoreOrgEntity coreOrg = orgService.selectById(orgId);
        //根节点
        String parentName = "";
        if (new Integer(0).equals(coreOrg.getParentId())) {
            parentName = "根节点";
        } else {
            TabCoreOrgEntity parentOrg = orgService.selectById(coreOrg.getParentId());
            parentName = parentOrg.getOrgName();
        }
        request.setAttribute("org", coreOrg);
        request.setAttribute("parentName", parentName);
        return "/org/orgUpdate";
    }

    /**
     * 更新部门
     *
     * @param orgRequest
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/orgUpdate")
    @ResponseBody
    public ResponseEntity<ResponseDto> treeUpdate(OrgRequest orgRequest) {
        // 校验参数
        ValidateResult<OrgRequest> validateResult = paramCheckLogic.checkParamValidate(orgRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabCoreOrgEntity coreOrg = new TabCoreOrgEntity();
        BeanUtils.copyProperties(orgRequest, coreOrg);

        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        Integer userId = currentUser.getUserId();
        coreOrg.setLastModifyId(userId);
        coreOrg.setLastModifyTime(new Date());
        int num = orgService.update(coreOrg);
        if (num == 1) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("系统错误"), HttpStatus.OK);
    }

    /**
     * 删除校验
     * @param request
     * @param orgIds
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/orgDeleteCheck")
    public ResponseEntity<ResponseDto> orgDeleteCheck(HttpServletRequest request, Integer[] orgIds) {
        LogUtil.info(LOGGER, "orgIds:{}", orgIds);
        List<TabCoreOrgEntity> orgList = orgService.selectByParentIds(orgIds);
        if (Check.isNullCollection(orgList)) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 逻辑批量删除部门信息
     *
     * @param request
     * @param orgIds
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/orgDelete")
    public ResponseEntity<ResponseDto> orgDelete(HttpServletRequest request, Integer[] orgIds) {
        LogUtil.info(LOGGER, "orgIds:{}", orgIds);
        int num = orgService.deleteLogicByIds(orgIds);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    private OrgRequest getJsonToTaskRequest(HttpServletRequest request){
    	String logJson = request.getParameter("request_json");
    	LogUtil.info(LOGGER, "logJson:{}", logJson);
    	OrgRequest orgRequest = (OrgRequest)JsonEntityTransform.json2Object(logJson, OrgRequest.class);
    	return orgRequest;
    }
}
